package com.cx.wechat.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.cx.wechat.config.WxMaConfiguration;
import com.cx.wechat.utils.WxJsonUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.io.File;

import java.util.ArrayList;
import java.util.List;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/wx/user")
public class WxMaUserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 生成小程序二维码 带参数 跳转页面
     * @return
     * @throws WxErrorException
     */
    @ResponseBody
    @GetMapping("/miniCode")
    public File miniCode() throws WxErrorException {
        WxMaService maService = WxMaConfiguration.getMaService("wxb3b2cb26e1695554");
        File wxaCodeUnlimit = maService.getQrcodeService().createWxaCodeUnlimit("partId:1", "pages/index/index");
        return wxaCodeUnlimit;
    }


    /**
     * 登陆接口
     */
    @GetMapping("/login")
    public String login(@PathVariable String appid, String code) throws WxErrorException {
        WxMaService maService = WxMaConfiguration.getMaService(appid);
        if (StringUtils.isBlank(code)) {
            return "empty jscode";
        }

        final WxMaService wxService = maService;

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            //TODO 可以增加自己的逻辑，关联业务相关数据

            WxMaSubscribeMessage message = new WxMaSubscribeMessage();
            message.setTemplateId("lmB66i1wp111z7D1X71tCmJ6Ay4wiOizMvBWs2XKRu4");
            message.setToUser(session.getOpenid());
            List<WxMaSubscribeMessage.Data> list = new ArrayList<>();
            list.add(new WxMaSubscribeMessage.Data("name1","测试昵称"));
            list.add(new WxMaSubscribeMessage.Data("time2","2020-04-29"));
            list.add(new WxMaSubscribeMessage.Data("thing4","测试注意事项"));
            message.setData(list);
            message.setPage("/pages/order/index");
            message.setMiniprogramState("developer");
            maService.getMsgService().sendSubscribeMsg(message);

            return WxJsonUtils.toJson(session);
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return e.toString();
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/info")
    public String info(@PathVariable String appid, String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

        return WxJsonUtils.toJson(userInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

        return WxJsonUtils.toJson(phoneNoInfo);
    }

}
